package com.ld.businesscard_manage.controller.user;

import com.ld.businesscard_manage.bean.User;
import com.ld.businesscard_manage.service.UserService;
import com.ld.businesscard_manage.service.impl.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class RegisterController extends HttpServlet {
	private UserService userService = new UserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String username = req.getParameter("username");
		if(!req.getParameter("password").equals(req.getParameter("repassword"))){
			PrintWriter writer = resp.getWriter();
			writer.println("<h1>两次输入的密码不一致</h1>");
			writer.println("<a href='/register.jsp'>返回注册页</a>");
			writer.flush();
			writer.close();
		}else {
			String password = DigestUtils.md5Hex(req.getParameter("password"));
			User userByName = userService.getUserByName(username);
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			user.setStatus(0);
			if (userByName != null) {
				PrintWriter writer = resp.getWriter();
				writer.println("<h1>该用户已经存在</h1>");
				writer.println("<a href='/index.jsp'>返回注册页</a>");
				writer.flush();
				writer.close();
			} else if (username.equals("") || password.equals("")) {
				PrintWriter writer = resp.getWriter();
				writer.println("<h1>密码不能为空</h1>");
				writer.println("<a href='/index.jsp'>返回注册页</a>");
				writer.flush();
				writer.close();
			} else {
				int i = userService.addUser(user);
				if (i == 0) {
					PrintWriter writer = resp.getWriter();
					writer.println("<h1>注册失败</h1>");
					writer.println("<a href='/index.jsp'>返回注册页</a>");
					writer.flush();
					writer.close();
				} else {
					HttpSession session = req.getSession();
					session.setAttribute("user", user);
					req.getRequestDispatcher("/home/application.jsp").forward(req, resp);
				}

			}
		}


	}
}
